package ldh.im.admin.interceptor;

import ldh.im.admin.exception.ErrorStatus;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;

@Component
public class TokenInterceptor implements HandlerInterceptor {

    private static final Logger LOGGER = LoggerFactory.getLogger(TokenInterceptor.class);
    private static final List<String> ignoreUrls = Arrays.asList("/client/imLogin", "/client/token/refresh", "/webrtc/");

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String url = request.getRequestURI();
        boolean isMatch = ignoreUrls.stream().anyMatch(u->url.startsWith(u));
        if (isMatch) return true;
        String token = request.getHeader("im.token");
        if (StringUtils.isEmpty(token)) {
            LOGGER.error("未登录，不能访问");
            ErrorStatus.No_login.throwException();
        }
        LOGGER.info("{} request {}", request.getRequestURI(), request.getMethod());
        return true;
    }
}